package com.ad.aidai.fragments.create_order;

import android.content.Context;
import android.view.Gravity;

import com.ad.aidai.bean.Order;
import com.ad.aidai.bean.Place;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.ad.aidai.network.result.NetResultWithData;
import com.flyco.dialog.entity.DialogMenuItem;
import com.mingle.entity.MenuEntity;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * CreateOrderPresenter
 * <p>
 * Created by Yusxon on 17/1/18.
 */

public class CreateOrderPresenter implements CreateOrderContract.Presenter {

    private Context mContext;
    private CreateOrderContract.View mView;

    private ArrayList<DialogMenuItem> orderTypeMenuItems;

    private int orderType = -1;
    private Place pushPlace = null;
    private PushTimeBean pushTimeBean = null;

    private List<MenuEntity> pushPlaceMenuEntity;
    private List<Place> placeList;
    private List<PushTimeBean> pushTimeList;
    private List<MenuEntity> pushTimeMenuEntity;

    class PushTimeBean {
        private String pTime;
        private long lTime;

        public PushTimeBean(String pTime, long lTime) {
            this.pTime = pTime;
            this.lTime = lTime;
        }

        public String getpTime() {
            return pTime;
        }

        public void setpTime(String pTime) {
            this.pTime = pTime;
        }

        public long getlTime() {
            return lTime;
        }

        public void setlTime(long lTime) {
            this.lTime = lTime;
        }
    }

    public CreateOrderPresenter(Context context, CreateOrderContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        initData();
    }

    private void initData() {
        placeList = ADApp.getPlaces();
        orderTypeMenuItems = new ArrayList<>();
        orderTypeMenuItems.add(new DialogMenuItem("代拿", 0));
        orderTypeMenuItems.add(new DialogMenuItem("代买", 0));
        orderTypeMenuItems.add(new DialogMenuItem("代办", 0));

        pushPlaceMenuEntity = new ArrayList<>();
        pushTimeMenuEntity = new ArrayList<>();
        //添加假数据

        String[] pTime = {"立即推送", "五分钟后", "十分钟后", "三十分钟后", "一小时后"};
        long[] lTime = {0L, 5 * 60 * 1000L, 10 * 60 * 1000L, 30 * 60 * 1000L, 60 * 60 * 1000L};
        pushTimeList = new ArrayList<>();

        for (int i = 0; i < pTime.length; ++i) {
            pushTimeList.add(new PushTimeBean(pTime[i], lTime[i]));
            pushTimeMenuEntity.add(new MenuEntity(pTime[i]).setGravity(Gravity.CENTER));
        }
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unSubscribe() {

    }

    @Override
    public ArrayList<DialogMenuItem> getTypeMenuItem() {
        return orderTypeMenuItems;
    }

    @Override
    public void chooseTypeMenuItem(int position) {
        orderType = position;
        mView.showOrderType(orderTypeMenuItems.get(position).mOperName);
    }

    @Override
    public void submit() {
        String orderContent = mView.getOrderContent();
        String orderDeliveryAddress = mView.getOrderAddressOfDelivery();
        String endTime = mView.getEndTime();
        String rewardMoney = mView.getRewardMoney();
        if (orderType == -1) {
            mView.toast("请选择爱代单类型");
        } else if (CheckUtil.checkStrNull(orderContent)) {
            mView.toast("请输入爱代单内容");
        } else if (pushPlace == null) {
            mView.toast("请选择推送地点");
        } else if (pushTimeBean == null) {
            mView.toast("请选择推送时间");
        } else if (CheckUtil.checkStrNull(endTime)) {
            mView.toast("请设置爱代单有效截止时间");
        } else if (CheckUtil.checkStrNull(rewardMoney)) {
            mView.toast("请输入酬劳");
        } else {
            long currentTime = System.currentTimeMillis();
            String realPushTime = getDateToString(currentTime + pushTimeBean.getlTime());

            Map<String, String> maps = new HashMap<>();
            maps.put("orderType", orderType + "");
            maps.put("orderStatus", Order.STATUS_NO_RECIEVE + "");
            maps.put("orderContent", orderContent);
            maps.put("orderReward", rewardMoney);
            maps.put("orderSendTime", realPushTime);
            maps.put("orderExpireTime", endTime);
            maps.put("orderExchnPlace", orderDeliveryAddress);
            maps.put("orderSendId", ADApp.getUser().getUserId() + "");
            maps.put("placeId", pushPlace.getPlaceId() + "");
            maps.put("orderTime", realPushTime);
            Logger.i(maps.toString());
            submit(maps);
        }
    }

    private String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    private void submit(Map<String, String> maps) {
        mView.showLoading();
        NetWork.getOrderOperationApi()
                .sendOrder(maps)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("CreateOrderPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        Logger.t("CreateOrderPresenter").i(result.toString());
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            mView.sendSuccess();
                        } else {
                            mView.closeLoading(false);
                        }
                    }
                });
    }

    @Override
    public List<MenuEntity> getPushPlaceMenuEntity() {
        return pushPlaceMenuEntity;
    }

    @Override
    public List<MenuEntity> getPushTimeMenuEntity() {
        return pushTimeMenuEntity;
    }

    @Override
    public void selectPushPlace(int position) {
        pushPlace = placeList.get(position);
        mView.showPushPlace(pushPlace.getPlaceName());
    }

    @Override
    public void selectPushTime(int position) {
        pushTimeBean = pushTimeList.get(position);
        mView.showPushTime(pushTimeBean.getpTime());
    }

    @Override
    public void openPushAddress() {
        if (placeList != null && placeList.size() > 0) {
            pushPlaceMenuEntity.clear();
            for (Place place : placeList) {
                pushPlaceMenuEntity.add(new MenuEntity(place.getPlaceName()).setGravity(Gravity
                        .CENTER));
            }
            mView.openPushAddress();
        } else {
            mView.showLoadingWithoutAnim();
            NetWork.getOrderOperationApi()
                    .getPlaceBySchoolId(ADApp.getUser().getSchoolId())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<NetResultWithData<List<Place>>>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            Logger.t("CreateOrderPresenter").e(e.getMessage());
                            mView.closeLoading(false);
                        }

                        @Override
                        public void onNext(NetResultWithData<List<Place>> result) {
                            Logger.t("CreateOrderPresenter").i(result.toString());
                            if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                                mView.closeLoading(true);
                                placeList.clear();
                                placeList.addAll(result.getData());
                                pushPlaceMenuEntity.clear();
                                for (Place place : placeList) {
                                    pushPlaceMenuEntity.add(new MenuEntity(place.getPlaceName()).setGravity(Gravity
                                            .CENTER));
                                }
                                mView.openPushAddress();
                            } else {
                                mView.closeLoading(false);
                            }
                        }
                    });
        }
    }
}
